package com.hngm.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hngm.bean.Company;
import com.hngm.bean.Product;
import com.hngm.common.Result;
import com.hngm.common.ResultList;
import com.hngm.dao.CompanyDao;

/**
 * Servlet implementation class ConpanyServlet
 */
public class ConpanyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ConpanyServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		//获取请求中的参数url
		String url = request.getParameter("url");
		
		CompanyDao companyDao = new CompanyDao();
		if("querycompany".equals(url)){
			//获取前端传过来的查询条件
			String companyname = request.getParameter("companyname");
			//根据传过来得查询条件去查询产品列表
			ArrayList<Company> pList = companyDao.queryCompanyListByParm(companyname);
			
			//查询数据库中的数量
			int count = companyDao.queyrCompanyListByParamCount();
			
			//返回给调用者一个JSON格式的字符串
			//将获取到的产品列表转换成符合Layui要求格式的JSON字符串
			String str = ResultList.toClient(0, "成功", count, pList);
			out.print(str);
		}else if("edit".equals(url)){
			//编辑企业信息逻辑
			//1、编辑用户有输入的企业信息
			long id = Long.parseLong(request.getParameter("id"));
			String name = request.getParameter("name");
			String address = request.getParameter("address");
			String websiteurl = request.getParameter("websiteurl");
			String shortintroduction = request.getParameter("shortintroduction");
			String introduction = request.getParameter("introduction");
			String hotline = request.getParameter("hotline");
			String phone = request.getParameter("phone");
			String mailbox = request.getParameter("mailbox");
			String culture = request.getParameter("culture");
			Company p = new Company(id, name, address, websiteurl, shortintroduction, introduction, hotline, phone, mailbox, culture);
			//2、将产品信息插入到表中（调用DAO）
			int result = companyDao.editCompany(p);
			//3、返回结果前端

			if(result > 0){
				//成功 返回JSON类型的处理结果
				out.print(Result.toClient(true, "添加成功"));
				
			}else{
				//失败
				out.print(Result.toClient(false, "添加失败"));
			}
		
		}
		out.flush();
		out.close();
			
		}
		

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
